//
//  SGTopScrollMenu.m
//  SGTopScrollMenu
//
//  Created by Sorgle on 16/8/14.
//  Copyright © 2016年 Sorgle. All rights reserved.
//

// 欢迎来Github上下载最完整的Demo
// Github下载地址 https://github.com/Hanymore/SGTopScrollMenu.git


#import "SGTopScrollMenu.h"
#import "UIView+SGExtension.h"

#define labelFontOfSize [UIFont systemFontOfSize:15]
#define SG_screenWidth [UIScreen mainScreen].bounds.size.width

@interface SGTopScrollMenu ()
{
    UIColor *_normalColor;
    UIColor *_selColor;
}
@property (nonatomic, strong) UILabel *titleLabel;
/** 选中时的label */
@property (nonatomic, strong) UILabel *selectedLabel;
/** 指示器 */
@property (nonatomic, strong) UIView *indicatorView;
//计算所有文本宽度
@property (nonatomic, strong) NSMutableArray *allLabelWidthArr;

@end


@implementation SGTopScrollMenu

/** label之间的间距 */
static CGFloat const labelMargin = 15;
/** 指示器的高度 */
static CGFloat const indicatorHeight = 3;
/** 形变的度数 */
static CGFloat const radio = 1.0;

- (NSMutableArray *)allTitleLabel {
    if (_allTitleLabel == nil) {
        _allTitleLabel = [NSMutableArray array];
    }
    return _allTitleLabel;
}

- (NSMutableArray *)allLabelWidthArr{
    if (!_allLabelWidthArr) {
        _allLabelWidthArr = [NSMutableArray arrayWithCapacity:0];
    }
    return _allLabelWidthArr;
}

//- (instancetype)initWithFrame:(CGRect)frame {
//    if (self = [super initWithFrame:frame]) {
//        self.backgroundColor = [UIColor whiteColor];
//        self.showsHorizontalScrollIndicator = NO;
//        self.bounces = NO;
//
//        self.indicatorColor = [UIColor colorWithRed:244 / 255.0f green:51 / 255.0f blue:51 / 255.0f alpha:1];
//    }
//    return self;
//}

- (CGSize)intrinsicContentSize{
    return UILayoutFittingExpandedSize;
}


+ (instancetype)topScrollMenuWithFrame:(CGRect)frame NormalColor:(UIColor *)normalColor SelColor:(UIColor *)selColor {
    
    return [[self alloc] initWithFrame:frame NormalColor:normalColor SelColor:selColor];
}

- (instancetype)initWithFrame:(CGRect)frame NormalColor:(UIColor *)normalColor SelColor:(UIColor *)selColor{
    if (self = [super initWithFrame:frame]) {
        self.backgroundColor = [UIColor whiteColor];
        self.showsHorizontalScrollIndicator = NO;
        self.bounces = NO;
        _normalColor = normalColor;
        _selColor = selColor;
        
        self.indicatorColor = [UIColor colorWithRed:244 / 255.0f green:51 / 255.0f blue:51 / 255.0f alpha:1];
    }
    return self;
}

/**
 *  计算文字尺寸
 *
 *  @param text    需要计算尺寸的文字
 *  @param font    文字的字体
 *  @param maxSize 文字的最大尺寸
 */
- (CGSize)sizeWithText:(NSString *)text font:(UIFont *)font maxSize:(CGSize)maxSize {
    NSDictionary *attrs = @{NSFontAttributeName : font};
    return [text boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:attrs context:nil].size;
}


- (void)setTitlesArr:(NSArray *)titlesArr {
    _titlesArr = titlesArr;
    
    /** 创建标题Label */
    CGFloat labelX = 0;
    CGFloat labelY = 0;
    CGFloat labelH = self.frame.size.height - indicatorHeight;
    
    for (NSUInteger i = 0; i < self.titlesArr.count; i++) {
        self.titleLabel = [[UILabel alloc] init];
        _titleLabel.userInteractionEnabled = YES;
        _titleLabel.text = self.titlesArr[i];
        _titleLabel.textColor = _normalColor;
        // 设置高亮文字颜色
        _titleLabel.highlightedTextColor = _selColor;

        _titleLabel.tag = i;
        _titleLabel.textAlignment = NSTextAlignmentCenter;
        
        // 计算内容的Size
        CGSize labelSize = [self sizeWithText:_titleLabel.text font:labelFontOfSize maxSize:CGSizeMake(MAXFLOAT, labelH)];
        
        // 计算内容的宽度
        CGFloat labelW = labelSize.width + 2 * labelMargin;
        [self.allLabelWidthArr addObject:[NSNumber numberWithFloat:labelW]];

        _titleLabel.frame = CGRectMake(labelX, labelY, labelW, labelH);
        
        // 计算每个label的X值
        labelX = labelX + labelW;
        
        // 添加到titleLabels数组
        [self.allTitleLabel addObject:_titleLabel];
        
        // 添加点按手势
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(titleClick:)];
        [_titleLabel addGestureRecognizer:tap];
        
        // 默认选中第0个label
        if (i == 0) {
            [self titleClick:tap];
        }

        [self addSubview:_titleLabel];
        [self bringSubviewToFront:_titleLabel];
    }
    
    //判断宽度
    CGFloat allWidth = 0;
    for (NSNumber *labelWidth in self.allLabelWidthArr) {
        allWidth += [labelWidth floatValue];
    }
    
    if (allWidth < SG_screenWidth) {
        for (int i = 0; i < self.allTitleLabel.count; i++) {
            UILabel *label = self.allTitleLabel[i];
            label.frame = CGRectMake(i * (self.frame.size.width / self.allTitleLabel.count), label.frame.origin.y, self.frame.size.width / self.allTitleLabel.count, label.frame.size.height);
        }
    }
    
    // 计算scrollView的宽度
    CGFloat scrollViewWidth = CGRectGetMaxX(self.subviews.lastObject.frame);
    self.contentSize = CGSizeMake(scrollViewWidth, self.frame.size.height);
    
    // 取出第一个子控件
    UILabel *firstLabel = self.subviews.firstObject;
    
    // 添加指示器
    if (self.titlesArr.count > 1) {
        self.indicatorView = [[UIView alloc] init];
        _indicatorView.backgroundColor = _selColor;
        _indicatorView.SG_height = indicatorHeight;
        _indicatorView.SG_y = self.frame.size.height - indicatorHeight;
        [self addSubview:_indicatorView];
    }
    // 计算内容的Size
    CGSize labelSize = [self sizeWithText:firstLabel.text font:labelFontOfSize maxSize:CGSizeMake(MAXFLOAT, labelH)];
    // 立刻根据文字内容计算第一个label的宽度
    _indicatorView.SG_width = labelSize.width;
    _indicatorView.SG_centerX = firstLabel.SG_centerX;
}

#pragma mark - - - Label的点击事件
- (void)titleClick:(UITapGestureRecognizer *)tap {
    // 0.获取选中的label
    UILabel *selLabel = (UILabel *)tap.view;
    
    // 1.标题颜色变成红色,设置高亮状态下的颜色， 以及指示器位置
    [self selectLabel:selLabel];
    
    // 2.让选中的标题居中
    [self setupTitleCenter:selLabel];
    
    
    NSInteger index = selLabel.tag;
    if ([self.topScrollMenuDelegate respondsToSelector:@selector(SGTopScrollMenu:didSelectTitleAtIndex:)]) {
        [self.topScrollMenuDelegate SGTopScrollMenu:self didSelectTitleAtIndex:index];
    }
}

/** 选中label标题颜色变成红色以及指示器位置 */
- (void)selectLabel:(UILabel *)label {
    // 取消高亮
    _selectedLabel.highlighted = NO;
    // 取消形变
    _selectedLabel.transform = CGAffineTransformIdentity;
    // 颜色恢复
    _selectedLabel.textColor = _normalColor;
    
    // 高亮
    label.highlighted = YES;
    // 形变
    label.transform = CGAffineTransformMakeScale(radio, radio);
    
    _selectedLabel = label;
    
    // 计算内容的Size
    CGSize labelSize = [self sizeWithText:label.text font:labelFontOfSize maxSize:CGSizeMake(MAXFLOAT, label.height)];

    // 改变指示器位置
    [UIView animateWithDuration:0.20 animations:^{
        self.indicatorView.SG_width = labelSize.width;
        self.indicatorView.SG_centerX = label.SG_centerX;
    }];
}

/** 设置选中的标题居中 */
- (void)setupTitleCenter:(UILabel *)centerLabel {
    UILabel *lastLabel = self.allTitleLabel.lastObject;
    CGFloat maxX = CGRectGetMaxX(lastLabel.frame);
    if (maxX <= self.frame.size.width) {
        return;
    }
    // 计算偏移量
    CGFloat offsetX = centerLabel.center.x - self.frame.size.width * 0.5;
    
    if (offsetX < 0) offsetX = 0;
    
    // 获取最大滚动范围
    CGFloat maxOffsetX = self.contentSize.width - self.frame.size.width;
    
    if (offsetX > maxOffsetX) offsetX = maxOffsetX;
    
    // 滚动标题滚动条
    [self setContentOffset:CGPointMake(offsetX, 0) animated:YES];
}

- (void)setIndicatorColor:(UIColor *)indicatorColor{
    _indicatorColor = indicatorColor;
    self.indicatorView.backgroundColor = indicatorColor;
}

@end


